package com.lee.interceptor;


import com.lee.annotation.ResponseResult;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * TODO
 *
 * @className: ResponseResultInterceptor
 * @author: lx
 * @date: 2021-01-15
 **/
@Component
public class ResponseResultInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 判断是否标记@ResponseResult
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Class<?> beanType = handlerMethod.getBeanType();
            Method method = handlerMethod.getMethod();
            if (beanType.isAnnotationPresent(ResponseResult.class)) {
                request.setAttribute("RESPONSE-RESULT-ANN", beanType.getAnnotation(ResponseResult.class));
            } else if (method.isAnnotationPresent(ResponseResult.class)) {
                request.setAttribute("RESPONSE-RESULT-ANN", method.getAnnotation(ResponseResult.class));
            }
        }

        return true;
    }
}
